import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import os
import openpyxl


def saveData(file_path, data):
    if os.path.exists(file_path):
        # 打开现有的 Excel 文件
        workbook = openpyxl.load_workbook(file_path)
        # 选择要追加数据的工作表
        sheet = workbook.active  # 或者通过名称选择工作表： sheet = workbook['Sheet1']
    else:
        # 创建一个工作簿 或打开一个
        workbook = openpyxl.Workbook()
        # 选择默认的活动工作表
        sheet = workbook.active
        # 设置列名
        columns = ["产品名称", "短评价", "长评价"]
        sheet.append(columns)

    sheet.append(data)
    # 保存工作簿为 Excel 文件
    workbook.save(file_path)


def getData(url):
    # 打开网页
    driver.get(url)
    time.sleep(6)

    # 查找所有a标签中data-hook="product-link"的元素
    product_links = driver.find_element(By.CSS_SELECTOR, 'a[data-hook="product-link"]').text
    # 查找所有div标签中data-hook="review"的元素
    review_elements = driver.find_elements(By.CSS_SELECTOR, 'div[data-hook="review"]')
    # 打印找到的元素内容
    for review_element in review_elements:
        short_content = review_element.find_element(By.CSS_SELECTOR, 'span.cr-original-review-content').text
        content = review_element.find_element(By.CSS_SELECTOR, 'span[data-hook="review-body"]').text
        item = [product_links, short_content, content]
        saveData('./50美元以上_好评.xlsx', item)


# 创建Chrome浏览器实例
driver = webdriver.Chrome()

products_id = ['B007D26Y76', 'B002NSM3X4', 'B00PFXMOZQ', 'B095G7PB3D', 'B078PSWVBC']
for product in products_id:
    for i in range(1, 4):
        url = 'https://www.amazon.com/-/zh/product-reviews/{}/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&filterByStar=positive&reviewerType=avp_only_reviews&pageNumber={}'.format(product, i)
        getData(url)

# 关闭浏览器
driver.quit()


